# -*- coding: utf-8 -*-

import pytest

from appium import webdriver
from appium.options.android import UiAutomator2Options
from appium.webdriver.appium_service import AppiumService

# 开启服务端
APPIUM_HOST = '127.0.0.1'
APPIUM_PORT = 4723
@pytest.fixture(scope="session")
def start_appium_service():
    server = AppiumService()
    server.start(args=['--address', APPIUM_HOST, '-p', str(APPIUM_PORT)], timeout_ms=60000)
    yield server
    server.stop()

# 创建客户端到服务端的会话
def create_appium_session_by_api(custom_opts = None, appium_host = APPIUM_HOST, appium_port = APPIUM_PORT):
    options = UiAutomator2Options()
    if custom_opts is not None:
        options.load_capabilities(custom_opts)
    return webdriver.Remote(f'http://{appium_host}:{appium_port}', options=options)


def test_get_settings(start_appium_service):
    custom_opts = {
        "appium:avd": "testPhone",
    }

    driver = create_appium_session_by_api(custom_opts)

    settings = driver.get_settings()
    assert settings["actionAcknowledgmentTimeout"] == 3000


def test_set_settings_in_capabilities(start_appium_service):
    custom_opts = {
        "appium:settings[actionAcknowledgmentTimeout]": 4321,
        "appium:avd": "testPhone",
    }

    driver = create_appium_session_by_api(custom_opts)

    settings = driver.get_settings()
    assert settings["actionAcknowledgmentTimeout"] == 4321


def test_set_settings(start_appium_service):
    custom_opts = {
        "appium:avd": "testPhone",
    }

    driver = create_appium_session_by_api(custom_opts)

    settings = driver.get_settings()
    assert settings["actionAcknowledgmentTimeout"] == 3000

    modify_args = {
        "actionAcknowledgmentTimeout": 4321,
    }
    driver.update_settings(modify_args)

    settings = driver.get_settings()
    assert settings["actionAcknowledgmentTimeout"] == 4321


def test_settings_elementResponseAttributes(start_appium_service):
    custom_opts = {
        "appium:avd": "testPhone",
    }

    driver = create_appium_session_by_api(custom_opts)

    driver.update_settings({"shouldUseCompactResponses":False})
    settings = driver.get_settings()
    assert settings["shouldUseCompactResponses"] == False

    resp_attr = settings["elementResponseAttributes"]
    assert "selected" not in resp_attr

    resp_attr += ",selected"
    driver.update_settings({"elementResponseAttributes": resp_attr})

    settings = driver.get_settings()
    assert "selected" in settings["elementResponseAttributes"]

    driver.quit()